<template>
  <nav-bar />
  <view class="goods-add-page">
    <!-- 顶部导航 -->
    <view class="nav-bar">
      <text class="nav-back" @click="onBack">&#8592;</text>
      <text class="nav-title">添加商品</text>
    </view>

    <!-- 多图横向滚动 -->
    <scroll-view 
      class="goods-img-list-horizontal" 
      scroll-x 
      :scroll-with-animation="true"
      :enhanced="true"
      :show-scrollbar="false"
      :bounces="true"
      @touchstart.passive="onTouchStart"
      @touchmove.passive="onTouchMove"
      @touchend.passive="onTouchEnd"
    >
      <view class="img-list-row">
        <view class="img-box-horizontal" v-for="(img, index) in form.images" :key="index">
          <image class="goods-img-horizontal" :src="img" mode="aspectFill" />
          <view class="img-delete-horizontal" @click="onImgDelete(index)">×</view>
        </view>
        <!-- 上传按钮 -->
        <view class="img-box-horizontal add-img-horizontal" @click="onAddImg">
          <text class="add-icon-horizontal">+</text>
        </view>
      </view>
    </scroll-view>

    <!-- 商品ID输入框 -->
    <view class="product-id-section">
      <text class="product-id-label">商品ID：</text>
      <view class="product-id-value-wrap">
        <view class="input-scan-row">
          <input 
            type="text" 
            v-model="form.product_id" 
            class="product-id-input" 
            placeholder="请输入商品ID（可选）"
            :focus="inputFocused"
            @focus="inputFocused = true"
            @blur="inputFocused = false"
          />
          <button class="btn-scan" @click="onScanCode">
            <text class="iconfont icon-saoma"></text>
          </button>
        </view>
        <text class="input-tip">商品ID只能包含英文、数字、下划线和-</text>
      </view>
    </view>

    <!-- 表单区域 -->
    <view class="form-section">
      <view class="form-item required">
        <view class="label">商品名称</view>
        <input class="value-input" v-model="form.name" placeholder="请输入" maxlength="30" />
      </view>

      <view class="form-item" v-if="type === 'main'">
        <view class="label">主分类</view>
        <picker class="value-picker" :range="categoryList" range-key="name" @change="onCategoryChange">
          <view class="picker-value">{{ selectedCategory ? selectedCategory.name : '请选择' }}</view>
        </picker>
      </view>

      <view class="form-item" v-if="type === 'sub'">
        <view class="label">次分类</view>
        <picker class="value-picker" :range="subCategoryList" range-key="name" @change="onSubCategoryChange">
          <view class="picker-value">{{ selectedSubCategory ? selectedSubCategory.name : '请选择' }}</view>
        </picker>
      </view>

      <view class="form-item required">
        <view class="label">售价</view>
        <view class="value-row">
          <input class="value-input" v-model="form.price" type="digit" placeholder="请输入" />
          <text class="unit">元</text>
        </view>
      </view>

      <view class="form-item required">
        <view class="label">进货价</view>
        <view class="value-row">
          <input class="value-input" v-model="form.purchase_price" type="digit" placeholder="请输入" />
          <text class="unit">元</text>
        </view>
      </view>

      <view class="form-item required">
        <view class="label">库存</view>
        <view class="value-row">
          <input class="value-input" v-model="form.stock" type="number" placeholder="请输入" @input="onStockChange" />
          <text class="unit">个</text>
        </view>
      </view>

      <view class="form-item required">
        <view class="label">货架数量</view>
        <view class="value-row">
          <input class="value-input" v-model="form.shelf_number" type="number" placeholder="请输入" @input="onShelfNumberChange" />
          <text class="unit">个</text>
        </view>
      </view>

      <view class="form-item required">
        <view class="label">仓库数量</view>
        <view class="value-row">
          <input class="value-input" v-model="form.warehouse_number" type="number" placeholder="请输入" @input="onWarehouseNumberChange" />
          <text class="unit">个</text>
        </view>
      </view>

      <view class="form-item required">
        <view class="label">状态</view>
        <picker class="value-picker" :range="statusList" range-key="name" @change="onStatusChange">
          <view class="picker-value">{{ selectedStatus ? selectedStatus.name : '请选择' }}</view>
        </picker>
      </view>

      <view class="form-item required">
        <view class="label">上架员</view>
        <view class="value-row">
          <text class="value-text">{{ userInfo?.username || '-' }}</text>
        </view>
      </view>

      <view class="form-item" @click="showDescriptionPopup">
        <view class="label">描述</view>
        <view class="value-row description-preview">
          <text class="description-text">{{ form.description || '请输入' }}</text>
          <text class="arrow">></text>
        </view>
      </view>
    </view>

    <!-- 描述弹窗 -->
    <uni-popup ref="descriptionPopup" type="center">
      <view class="description-popup">
        <view class="popup-header">
          <text class="popup-title">商品描述</text>
          <text class="popup-close" @click="closeDescriptionPopup">×</text>
        </view>
        <view class="popup-content">
          <view class="history-section" v-if="descriptionHistory.length > 0">
            <view class="history-title">历史记录</view>
            <scroll-view class="history-list" scroll-y>
              <view 
                class="history-item" 
                v-for="(item, index) in descriptionHistory" 
                :key="index"
                @click="useHistoryDescription(item)"
              >
                <text class="history-text">{{ item }}</text>
                <text class="history-delete" @click.stop="deleteHistoryDescription(index)">×</text>
              </view>
            </scroll-view>
          </view>
          <textarea 
            class="description-textarea" 
            v-model="form.description" 
            placeholder="请输入商品描述"
            :maxlength="1000"
            show-confirm-bar="false"
          />
          <view class="word-count">{{ form.description.length }}/1000</view>
        </view>
        <view class="popup-footer">
          <button class="confirm-btn" @click="closeDescriptionPopup">确定</button>
        </view>
      </view>
    </uni-popup>

    <!-- 底部按钮 -->
    <view class="footer-bar">
      <button class="save-btn" @click="onSave">保存</button>
    </view>

    <!-- 自定义消息框组件 -->
    <message-box
      v-model="showMsgBox"
      :title="msgBoxTitle"
      :content="msgBoxContent"
      :showCancel="msgBoxShowCancel"
      :confirmText="msgBoxConfirmText"
      :cancelText="msgBoxCancelText"
      @confirm="onMsgBoxConfirm"
      @cancel="onMsgBoxCancel"
    />

    <!-- 自定义 Toast 组件 -->
    <toast
      v-model="showToast"
      :content="toastContent"
      :type="toastType"
      :duration="toastDuration"
    />
  </view>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue'
import { IntranetConfig, UserConfig } from '@/static/js/config'
import MessageBox from '@/components/message-box/message-box.vue'
import Toast from '@/components/toast/toast.vue'

// 定义 props
const props = defineProps({
  product_id: {
    type: String,
    default: ''
  }
})

// 获取页面参数
const pages = getCurrentPages()
const currentPage = pages[pages.length - 1]
const type = currentPage.$page?.options?.type || 'main'
const productId = props.product_id || decodeURIComponent(currentPage.$page?.options?.product_id || '')

// 获取用户信息
const userInfo = computed(() => UserConfig.getUserInfo())

// Toast 相关
const showToast = ref(false)
const toastContent = ref('')
const toastType = ref('')
const toastDuration = ref(2000)

function showCustomToast(content, type = '', duration = 2000) {
  toastContent.value = content
  toastType.value = type
  toastDuration.value = duration
  showToast.value = true
}

// 消息框相关
const showMsgBox = ref(false)
const msgBoxTitle = ref('')
const msgBoxContent = ref('')
const msgBoxShowCancel = ref(true)
const msgBoxConfirmText = ref('确定')
const msgBoxCancelText = ref('取消')
let msgBoxCallback = null

function openMsgBox({ title = '', content = '', showCancel = true, confirmText = '确定', cancelText = '取消', callback = null }) {
  msgBoxTitle.value = title
  msgBoxContent.value = content
  msgBoxShowCancel.value = showCancel
  msgBoxConfirmText.value = confirmText
  msgBoxCancelText.value = cancelText
  msgBoxCallback = callback
  showMsgBox.value = true
}

function onMsgBoxConfirm() {
  if (msgBoxCallback) msgBoxCallback(true)
}

function onMsgBoxCancel() {
  if (msgBoxCallback) msgBoxCallback(false)
}

// 表单数据
const form = ref({
  name: '',
  category: null,
  category_sub: null,
  price: '',
  purchase_price: '',
  stock: '',
  shelf_number: '',
  warehouse_number: '',
  status: 1,
  shelf_staff: userInfo.value?.id || '',
  description: '',
  images: [],
  product_id: productId
})

// 分类列表
const categoryList = ref([])
const subCategoryList = ref([])
const selectedCategory = ref(null)
const selectedSubCategory = ref(null)

// 状态列表
const statusList = ref([
  { id: 1, name: '正常' },
  { id: 2, name: '下架' }
])
const selectedStatus = ref(statusList.value[0])

// 描述弹窗
const descriptionPopup = ref(null)

// 记录最后一次修改的字段
let lastModifiedField = ''

// 获取分类列表
async function getCategoryList() {
  try {
    const [mainRes, subRes] = await Promise.all([
      uni.request({
        url: IntranetConfig.domain + 'api/category/get_category_list/',
        method: 'GET',
        header: IntranetConfig.headers
      }),
      uni.request({
        url: IntranetConfig.domain + 'api/category/get_category_sub_list/',
        method: 'GET',
        header: IntranetConfig.headers
      })
    ])
    
    if (mainRes.data.code === 200) {
      categoryList.value = mainRes.data.data
    }
    if (subRes.data.code === 200) {
      subCategoryList.value = subRes.data.data
    }
  } catch (error) {
    showCustomToast('获取分类失败', 'error')
  }
}

// 分类选择事件
function onCategoryChange(e) {
  const index = e.detail.value
  selectedCategory.value = categoryList.value[index]
  form.value.category = selectedCategory.value.id
  form.value.category_sub = null
  selectedSubCategory.value = null
}

function onSubCategoryChange(e) {
  const index = e.detail.value
  selectedSubCategory.value = subCategoryList.value[index]
  form.value.category_sub = selectedSubCategory.value.id
  form.value.category = null
  selectedCategory.value = null
}

// 状态选择事件
function onStatusChange(e) {
  const index = e.detail.value
  selectedStatus.value = statusList.value[index]
  form.value.status = selectedStatus.value.id
}

// 图片相关
function onAddImg() {
  uni.chooseImage({
    count: 9 - form.value.images.length,
    success: (res) => {
      form.value.images = [...form.value.images, ...res.tempFilePaths]
    }
  })
}

function onImgDelete(index) {
  form.value.images.splice(index, 1)
}

// 描述弹窗
function showDescriptionPopup() {
  descriptionPopup.value.open()
}

function closeDescriptionPopup() {
  // 如果描述不为空且不在历史记录中，则添加到历史记录
  if (form.value.description && !descriptionHistory.value.includes(form.value.description)) {
    descriptionHistory.value.unshift(form.value.description)
    // 保持历史记录数量不超过最大值
    if (descriptionHistory.value.length > MAX_HISTORY_COUNT) {
      descriptionHistory.value.pop()
    }
    saveDescriptionHistory()
  }
  descriptionPopup.value.close()
}

// 返回上一页
function onBack() {
  uni.navigateBack()
}

// 检查权限
function checkPermission() {
  if (!userInfo.value) {
    showCustomToast('请先登录', 'error')
    setTimeout(() => {
      uni.reLaunch({
        url: '/pages/login/login'
      })
    }, 1500)
    return false
  }

  if (userInfo.value.is_superuser !== 1 && userInfo.value.is_superuser !== 2) {
    showCustomToast('您没有添加商品的权限', 'error')
    setTimeout(() => {
      uni.navigateBack()
    }, 1500)
    return false
  }

  return true
}

// 库存变化时
function onStockChange() {
  if (lastModifiedField === 'stock') {
    const stock = parseInt(form.value.stock) || 0
    const shelfNumber = parseInt(form.value.shelf_number) || 0
    const warehouseNumber = parseInt(form.value.warehouse_number) || 0
    
    // 如果货架数量已填写，则自动计算仓库数量
    if (shelfNumber > 0) {
      form.value.warehouse_number = Math.max(0, stock - shelfNumber).toString()
    }
    // 如果仓库数量已填写，则自动计算货架数量
    else if (warehouseNumber > 0) {
      form.value.shelf_number = Math.max(0, stock - warehouseNumber).toString()
    }
  }
}

// 货架数量变化时
function onShelfNumberChange() {
  lastModifiedField = 'shelf'
  const stock = parseInt(form.value.stock) || 0
  const shelfNumber = parseInt(form.value.shelf_number) || 0
  
  // 自动计算仓库数量
  form.value.warehouse_number = Math.max(0, stock - shelfNumber).toString()
}

// 仓库数量变化时
function onWarehouseNumberChange() {
  lastModifiedField = 'warehouse'
  const stock = parseInt(form.value.stock) || 0
  const warehouseNumber = parseInt(form.value.warehouse_number) || 0
  
  // 自动计算货架数量
  form.value.shelf_number = Math.max(0, stock - warehouseNumber).toString()
}

// 修改保存函数中的验证逻辑
async function onSave() {
  // 检查权限
  if (!checkPermission()) return

  // 表单验证
  if (!form.value.name) {
    showCustomToast('请输入商品名称', 'error')
    return
  }
  if (!form.value.price) {
    showCustomToast('请输入商品价格', 'error')
    return
  }
  if (!form.value.purchase_price) {
    showCustomToast('请输入商品进货价', 'error')
    return
  }
  if (!form.value.stock) {
    showCustomToast('请输入商品库存', 'error')
    return
  }

  // 验证进货价和售卖价的关系
  if (parseFloat(form.value.purchase_price) >= parseFloat(form.value.price)) {
    const result = await new Promise((resolve) => {
      openMsgBox({
        title: '价格确认',
        content: '进货价大于或等于售卖价，是否确认继续？',
        showCancel: true,
        confirmText: '确认',
        cancelText: '取消',
        callback: resolve
      })
    })
    if (!result) return
  }

  // 验证分类选择
  if (type === 'main' && !form.value.category) {
    showCustomToast('请选择主分类', 'error')
    return
  }
  if (type === 'sub' && !form.value.category_sub) {
    showCustomToast('请选择次分类', 'error')
    return
  }

  // 验证库存、货架数量和仓库数量的关系
  const stock = parseInt(form.value.stock) || 0
  const shelfNumber = parseInt(form.value.shelf_number) || 0
  const warehouseNumber = parseInt(form.value.warehouse_number) || 0

  if (stock < 0) {
    showCustomToast('库存不能为负数', 'error')
    return
  }

  if (shelfNumber < 0) {
    showCustomToast('货架数量不能为负数', 'error')
    return
  }

  if (warehouseNumber < 0) {
    showCustomToast('仓库数量不能为负数', 'error')
    return
  }

  if (shelfNumber + warehouseNumber !== stock) {
    showCustomToast('货架数量和仓库数量之和必须等于库存', 'error', 3000)
    return
  }

  uni.showLoading({
    title: '保存中...',
    mask: true
  })

  try {
    // 构建请求数据
    const requestData = {
      name: form.value.name,
      price: form.value.price,
      purchase_price: form.value.purchase_price,
      stock: parseInt(form.value.stock),
      status: form.value.status,
      shelf_staff: userInfo.value.id,
      description: form.value.description || '',
      product_id: form.value.product_id,
      shelf_number: parseInt(form.value.shelf_number),
      warehouse_number: parseInt(form.value.warehouse_number)
    }
    if(requestData.shelf_number < 0 || requestData.warehouse_number < 0) {
      showCustomToast('货架数量和仓库数量不能为负数', 'error')
      return
    }
    if(requestData.shelf_number + requestData.warehouse_number !== requestData.stock) {
      showCustomToast('货架数量和仓库数量之和必须等于库存', 'error', 3000)
      return
    }

    // 根据类型添加分类字段
    if (type === 'main') {
      requestData.category = form.value.category
    } else {
      requestData.category_sub = form.value.category_sub
    }

    // 创建商品
    const createRes = await uni.request({
      url: IntranetConfig.domain + 'api/product/create_product/',
      method: 'POST',
      header: IntranetConfig.headers,
      data: requestData
    })

    if (createRes.data.code === 200) {
      const productId = createRes.data.data.id

      // 如果有图片，上传图片
      if (form.value.images.length > 0) {
        // 使用 Promise.all 处理所有图片上传
        const uploadPromises = form.value.images.map(imagePath => {
          return new Promise((resolve, reject) => {
            const uploadTask = uni.uploadFile({
              url: IntranetConfig.domain + `api/product/upload_product_image/${productId}/`,
              filePath: imagePath,
              fileType: 'image',
              name: 'image',
              formData: {
                product: productId.toString()
              },
              success: (res) => {
                try {
                  const data = JSON.parse(res.data)
                  if (data.code === 200) {
                    resolve(data)
                  } else {
                    reject(new Error(data.msg))
                  }
                } catch (e) {
                  reject(new Error('解析响应数据失败'))
                }
              },
              fail: (err) => {
                reject(new Error(err.errMsg || '上传失败'))
              }
            })

            // 监听上传进度
            uploadTask.onProgressUpdate((res) => {
              console.log('上传进度：', res.progress)
            })
          })
        })

        try {
          await Promise.all(uploadPromises)
          showCustomToast('添加成功', 'success')
        } catch (error) {
          console.error('图片上传错误：', error)
          showCustomToast('商品已创建，但图片上传失败', 'error', 2000)
        }
      } else {
        showCustomToast('添加成功', 'success')
      }

      setTimeout(() => {
        uni.navigateBack()
      }, 1500)
    } else {
      throw new Error(createRes.data.msg)
    }
  } catch (error) {
    console.error('保存商品错误：', error)
    showCustomToast(error.message || '添加失败', 'error')
  } finally {
    uni.hideLoading()
  }
}

// 页面加载
onMounted(() => {
  // 检查权限
  if (!checkPermission()) return
  getCategoryList()
  // 从本地存储加载历史记录
  const history = uni.getStorageSync('descriptionHistory')
  if (history) {
    descriptionHistory.value = JSON.parse(history)
  }
})

function copyProductId() {
  if (!form.value.product_id) return
  uni.setClipboardData({
    data: form.value.product_id,
    success: () => {
      showCustomToast('已复制', 'success')
    },
    fail: () => {
      showCustomToast('复制失败', 'error')
    }
  })
}

// 触摸事件处理
function onTouchStart(e) {
  // 可以在这里添加触摸开始的处理逻辑
}

function onTouchMove(e) {
  // 可以在这里添加触摸移动的处理逻辑
}

function onTouchEnd(e) {
  // 可以在这里添加触摸结束的处理逻辑
}

const inputFocused = ref(false)

// 扫码功能
function onScanCode() {
  uni.scanCode({
    scanType: ['barCode', 'qrCode'],
    success: (res) => {
      if (res.result) {
        form.value.product_id = res.result
      } else if (res.code) {
        form.value.product_id = res.code
      }
    },
    fail: (err) => {
      showCustomToast('扫码失败', 'error')
    }
  })
}

// 在 script setup 部分添加以下代码
const descriptionHistory = ref([])
const MAX_HISTORY_COUNT = 10

// 使用历史描述
function useHistoryDescription(description) {
  form.value.description = description
}

// 删除历史描述
function deleteHistoryDescription(index) {
  descriptionHistory.value.splice(index, 1)
  saveDescriptionHistory()
}

// 保存历史记录到本地存储
function saveDescriptionHistory() {
  uni.setStorageSync('descriptionHistory', JSON.stringify(descriptionHistory.value))
}
</script>

<style scoped lang="scss">
.goods-add-page {
  background: #f8f9fa;
  min-height: 100vh;
  padding-bottom: 120rpx;
  font-family: 'PingFang SC', 'Microsoft YaHei', Arial, sans-serif;
  overflow-x: hidden;
  max-width: 100vw;
  box-sizing: border-box;
}

.nav-bar {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 32rpx;
  height: 96rpx;
  background: #fff;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.05);
  position: sticky;
  top: 0;
  z-index: 100;
  
  .nav-back { 
    color: #333; 
    font-size: 44rpx;
    width: 80rpx;
    height: 80rpx;
    display: flex;
    align-items: center;
    justify-content: center;
    border-radius: 50%;
    transition: all 0.3s;
    
    &:active {
      background: rgba(0, 0, 0, 0.05);
    }
  }
  
  .nav-title { 
    flex: 1; 
    text-align: center; 
    font-size: 36rpx;
    font-weight: 600;
    color: #333;
  }
}

.goods-img-list-horizontal {
  width: 100%;
  overflow-x: auto;
  padding: 32rpx;
  background: #fff;
  margin-bottom: 24rpx;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.05);
  box-sizing: border-box;
  max-width: 100vw;
}

.img-list-row {
  display: flex;
  flex-direction: row;
  align-items: center;
  padding: 8rpx 0;
  box-sizing: border-box;
  max-width: 100vw;
}

.img-box-horizontal {
  position: relative;
  width: 160rpx;
  height: 160rpx;
  margin-right: 24rpx;
  border-radius: 16rpx;
  box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.08);
  background: #fff;
  display: flex;
  align-items: center;
  justify-content: center;
  flex-shrink: 0;
  transition: all 0.3s;
  
  &:active {
    transform: scale(0.98);
  }
  
  .goods-img-horizontal {
    width: 160rpx;
    height: 160rpx;
    border-radius: 16rpx;
    object-fit: cover;
  }
  
  .img-delete-horizontal {
    position: absolute;
    top: -16rpx;
    right: -16rpx;
    width: 44rpx;
    height: 44rpx;
    background: #ff7e2d;
    color: #fff;
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 32rpx;
    font-weight: bold;
    box-shadow: 0 4rpx 12rpx rgba(255, 126, 45, 0.3);
    z-index: 2;
    transition: all 0.3s;
    
    &:active {
      transform: scale(0.9);
      background: darken(#ff7e2d, 5%);
    }
  }
}

.add-img-horizontal {
  width: 160rpx;
  height: 160rpx;
  border-radius: 16rpx;
  border: 2rpx dashed #ff7e2d;
  background: #fff6ed;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.3s;
  
  &:active {
    transform: scale(0.98);
    background: darken(#fff6ed, 2%);
  }
  
  .add-icon-horizontal {
    font-size: 56rpx;
    color: #ff7e2d;
    font-weight: bold;
  }
}

.form-section {
  margin: 24rpx 32rpx;
  background: #fff;
  border-radius: 24rpx;
  box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.05);
  overflow: hidden;
  box-sizing: border-box;
  max-width: 100vw;
  
  .form-item {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 32rpx;
    border-bottom: 1rpx solid #f5f5f5;
    font-size: 30rpx;
    transition: all 0.3s;
    
    &:active {
      background: #fafafa;
    }
    
    &:last-child {
      border-bottom: none;
    }
    
    .label {
      color: #333;
      width: 180rpx;
      text-align: left;
      flex-shrink: 0;
      font-weight: 500;
    }
    
    .value-input {
      flex: 1;
      min-width: 0;
      border: none;
      background: transparent;
      font-size: 30rpx;
      color: #333;
      text-align: right;
      padding: 0;
      
      &::placeholder {
        color: #999;
      }
    }
    
    .value-picker {
      flex: 1;
      text-align: right;
      
      .picker-value {
        color: #333;
        font-size: 30rpx;
        
        &:empty::before {
          content: '请选择';
          color: #999;
        }
      }
    }
    
    .value-row {
      flex: 1;
      display: flex;
      align-items: center;
      justify-content: flex-end;
      min-width: 0;
    }
    
    .unit {
      color: #666;
      font-size: 26rpx;
      margin-left: 8rpx;
    }
    
    .arrow {
      color: #999;
      font-size: 28rpx;
      margin-left: 8rpx;
    }
  }
  
  .form-item.required .label:after {
    content: '*';
    color: #ff7e2d;
    margin-left: 4rpx;
  }
}

.description-preview {
  .description-text {
    flex: 1;
    color: #333;
    font-size: 30rpx;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
    max-width: 400rpx;
    
    &:empty::before {
      content: '请输入';
      color: #999;
    }
  }
}

.description-popup {
  width: 90vw;
  max-width: 600rpx;
  background: #fff;
  border-radius: 24rpx;
  overflow: hidden;
  box-shadow: 0 8rpx 32rpx rgba(0, 0, 0, 0.1);
  
  .popup-header {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 32rpx;
    border-bottom: 1rpx solid #f5f5f5;
    background: #fff;
    
    .popup-title {
      font-size: 32rpx;
      font-weight: 600;
      color: #333;
    }
    
    .popup-close {
      font-size: 40rpx;
      color: #999;
      padding: 16rpx;
      margin: -16rpx;
      border-radius: 50%;
      transition: all 0.3s;
      
      &:active {
        background: #f5f5f5;
      }
    }
  }
  
  .popup-content {
    padding: 32rpx;
    background: #fff;
    
    .history-section {
      margin-bottom: 24rpx;
      
      .history-title {
        font-size: 28rpx;
        color: #666;
        margin-bottom: 16rpx;
      }
      
      .history-list {
        max-height: 200rpx;
        margin-bottom: 16rpx;
        
        .history-item {
          display: flex;
          align-items: center;
          justify-content: space-between;
          padding: 16rpx;
          background: #f8f9fa;
          border-radius: 12rpx;
          margin-bottom: 12rpx;
          transition: all 0.3s;
          
          &:active {
            background: #f0f1f2;
          }
          
          .history-text {
            flex: 1;
            font-size: 28rpx;
            color: #333;
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;
            margin-right: 16rpx;
          }
          
          .history-delete {
            width: 40rpx;
            height: 40rpx;
            display: flex;
            align-items: center;
            justify-content: center;
            color: #999;
            font-size: 32rpx;
            border-radius: 50%;
            transition: all 0.3s;
            
            &:active {
              background: rgba(0, 0, 0, 0.05);
              color: #666;
            }
          }
        }
      }
    }
    
    .description-textarea {
      width: 100%;
      height: 400rpx;
      font-size: 30rpx;
      line-height: 1.6;
      color: #333;
      padding: 24rpx;
      background: #f8f9fa;
      border-radius: 16rpx;
      border: 1rpx solid #eee;
      box-sizing: border-box;
      
      &::placeholder {
        color: #999;
      }
    }
    
    .word-count {
      text-align: right;
      font-size: 24rpx;
      color: #999;
      margin-top: 16rpx;
    }
  }
  
  .popup-footer {
    padding: 24rpx 32rpx;
    border-top: 1rpx solid #f5f5f5;
    background: #fff;
    
    .confirm-btn {
      width: 100%;
      height: 88rpx;
      background: #ff7e2d;
      color: #fff;
      border: none;
      border-radius: 12rpx;
      font-size: 32rpx;
      font-weight: 500;
      transition: all 0.3s;
      
      &:active {
        transform: scale(0.98);
        background: darken(#ff7e2d, 5%);
      }
    }
  }
}

.footer-bar {
  position: fixed;
  left: 0;
  right: 0;
  bottom: 0;
  background: #fff;
  padding: 24rpx 32rpx calc(24rpx + env(safe-area-inset-bottom));
  box-shadow: 0 -4rpx 16rpx rgba(0, 0, 0, 0.05);
  
  .save-btn {
    width: 100%;
    height: 88rpx;
    background: #ff7e2d;
    color: #fff;
    border: none;
    border-radius: 12rpx;
    font-size: 32rpx;
    font-weight: 500;
    transition: all 0.3s;
    
    &:active {
      transform: scale(0.98);
      background: darken(#ff7e2d, 5%);
    }
  }
}

.value-text {
  color: #333;
  font-size: 30rpx;
}

.product-id-section {
  background: #fff;
  padding: 24rpx 32rpx;
  margin: 0 32rpx 24rpx;
  border-radius: 16rpx;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.05);
  
  .product-id-label {
    color: #666;
    font-size: 28rpx;
    font-weight: 500;
    margin-bottom: 16rpx;
    display: block;
  }
  
  .product-id-value-wrap {
    width: 100%;
    
    .input-scan-row {
      display: flex;
      align-items: center;
      gap: 18rpx;
      margin-bottom: 12rpx;
      
      .product-id-input {
        flex: 1;
        height: 90rpx;
        border: 2rpx solid #e5e5e5;
        border-radius: 16rpx;
        padding: 0 28rpx;
        font-size: 32rpx;
        background: #fafbfc;
        transition: border-color 0.2s, box-shadow 0.2s;
        outline: none;
        
        &::placeholder {
          color: #bbb;
        }
        
        &:focus {
          border-color: #ff7e2d;
          box-shadow: 0 2rpx 8rpx rgba(255, 126, 45, 0.10);
          background: #fff;
        }
      }
      
      .btn-scan {
        flex-shrink: 0;
        width: 90rpx;
        height: 90rpx;
        background: linear-gradient(90deg, #ffb86c 0%, #ff7e2d 100%);
        color: #fff;
        border: none;
        border-radius: 16rpx;
        display: flex;
        align-items: center;
        justify-content: center;
        box-shadow: 0 2rpx 8rpx rgba(255, 126, 45, 0.10);
        transition: all 0.2s;
        padding: 0;
        
        .iconfont {
          font-size: 40rpx;
        }
        
        &:active {
          transform: scale(0.95);
          background: linear-gradient(90deg, #ff7e2d 0%, #ffb86c 100%);
        }
      }
    }
    
    .input-tip {
      font-size: 24rpx;
      color: #999;
      margin-top: 8rpx;
      display: block;
      line-height: 1.5;
    }
  }
}
</style> 